package com.gopay.scheduler.shedulerx.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * if u has a good deal , please add it to make this class better
 */
public class ThreadPoolUtil {

    public static void shutdownGracefully(String poolName,ThreadPoolExecutor poolExecutor, TimeUnit timeUnit, long waitTime){
        if(poolExecutor != null && !poolExecutor.isShutdown()) {
            infoLog(String.format("{%s} pool_info = {%s}", poolName,poolExecutor.toString()));
            poolExecutor.shutdown();
            int queueSize = 0;
            try {
                if (!poolExecutor.awaitTermination(waitTime, timeUnit)) {
                     queueSize = poolExecutor.getQueue().size();
                    long var = queueSize / 10;
                    LOGGER.info(String.format("awaitTermination timeOut, retry block again ; {%s} pool_info = {%s}, queue size= %s ",poolName, poolExecutor.toString(),queueSize));
                    if(!poolExecutor.awaitTermination(var, TimeUnit.MILLISECONDS)){
                        LOGGER.info(String.format("awaitTermination timeOut again, retry block fail ; {%s} pool_info = {%s}, queue size= %s ", poolName,poolExecutor.toString(),queueSize));
                    }
                }
            } catch (InterruptedException e) {
                poolExecutor.shutdownNow();
                exceptionLog(e, String.format("{%s} pool_info = {%s}",poolName, poolExecutor.toString()));
            }
            infoLog(String.format("{%s} has been shutdown; queue size = {%s},", poolName,queueSize));
        }
    }

    private final static Logger LOGGER = LoggerFactory.getLogger(ThreadPoolUtil.class);
    private static void exceptionLog(Exception e,String description){
        LOGGER.error(String.format("the threadPool shutdown  occur error ,the description is {%s}",description),e);
    }
    private static void infoLog(String description){
        LOGGER.info(String.format("the thread shutdown log : {-->%s<--}",description));
    }

}
